package juc.utils.phaser;

import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

public class PhaserExample7 {
    private final static Random random = new Random(System.currentTimeMillis());

    /**
     * awaitAdvance()，给的phase值和当前phase值不相等则立即返回
     * awaitAdvance can decremental the arrived parties.
     */
    public static void main(String[] args) throws InterruptedException {

       /*final Phaser phaser = new Phaser(6);
        new Thread(()->phaser.awaitAdvance(0)).start();
        TimeUnit.SECONDS.sleep(3);
        System.out.println(phaser.getArrivedParties());
        //给的phase值和当前phase值相等会block
        phaser.awaitAdvance(phaser.getPhase());*/

        final Phaser phaser = new Phaser(7);
        IntStream.rangeClosed(0, 5).boxed().map(i -> phaser).forEach(AwaitAdvanceTask::new);
        phaser.awaitAdvance(phaser.getPhase());
        System.out.println("===");
    }

    private static class AwaitAdvanceTask extends Thread {
        private final Phaser phaser;

        public AwaitAdvanceTask(Phaser phaser) {
            this.phaser = phaser;
            //自启动，new的时候启动
            start();
        }

        @Override
        public void run() {
            timeSleep(2);
            //phaser.arriveAndAwaitAdvance();
            phaser.arrive();
            System.out.println(getName() + " finished work");
        }
    }

    private static void timeSleep(long time) {
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
